<?php

namespace App\Admin\Controllers;

use App\Models\Level;
use App\Models\User;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

class UserController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new User(), function (Grid $grid) {
            $grid->column('name');
            $grid->column('nickname');
            $grid->column('level_id')->display(function ($d) {
                return Level::find($d)->name;
            });
            $grid->column('is_manage')->display(function ($d) {
                return $d == 2 ? '管理员' : '普通用户';
            });
            $grid->column('status')->display(function () {
                return User::STATUS_ENUM[$this->status];
            });
            $grid->column('created_at');

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('name');
                $filter->equal('nickname');

            });

            $grid->showQuickEditButton();
            $grid->disableViewButton();
            $grid->disableEditButton();
        });
    }


    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new User(), function (Form $form) {
            $form->text('name');
            $form->text('nickname');
            $id = $form->getKey();
            if ($id) {
                $form->password('password', )
                    ->minLength(5)
                    ->maxLength(20)
                    ->customFormat(function () {
                        return '';
                    });
            } else {
                $form->password('password')
                    ->required()
                    ->minLength(5)
                    ->maxLength(20);
            }


            $form->select('level_id')->options(Level::query()->pluck('name', 'id'));
            $form->radio('is_manage')->options([
                '1' => '普通用户',
                '2' => '管理员',
            ])->default(1);
            $form->radio('status')->options(User::STATUS_ENUM)->default(1);



        })->saving(function (Form $form) {
            if ($form->password && $form->model()->get('password') != $form->password) {
                $form->password = bcrypt($form->password);
            }

            if (! $form->password) {
                $form->deleteInput('password');
            }
        });
    }
}
